#include "messageswindow.h"
#include "ui_messageswindow.h"
#include <QFile>
#include <QTextStream>
#include <limits>

MessagesWindow::MessagesWindow(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::MessagesWindow)
{
    m_ui->setupUi(this);
    this->setAttribute(Qt::WA_QuitOnClose, false);
    connect(m_ui->comboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateMessageCount(QString)));
}

MessagesWindow::~MessagesWindow()
{
    delete m_ui;
}

void MessagesWindow::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MessagesWindow::setMessageFilePath(const QString messfilepath)
{
    messfilename = messfilepath;
}

void MessagesWindow::updateMessageCount(const QString countstr)
{
    bool ok;
    int count = countstr.toInt(&ok);
    if (!ok)
        count = std::numeric_limits<int>::max();
    m_ui->textBrowser->clear();
    QFile messdb(messfilename);
    QStringList msglist;
    if (messdb.open(QIODevice::ReadOnly))
    {
        QTextStream stream(&messdb);
        do
        {
            QString message = stream.readLine(0);
            if (!message.isEmpty())
                msglist << message;
        } while (!stream.atEnd());

        for(int i=msglist.size()-1; ((i>=0)&&(i>=msglist.size()-count)); i--)
        {
            m_ui->textBrowser->insertHtml(msglist.at(i));
        }
        messdb.close();
    }

}
